package blog.service.impl;

import blog.entity.Article;
import blog.entity.CateGory;
import blog.entity.CateGory;
import blog.entity.Tag;
import blog.mapper.ArticleMapper;
import blog.mapper.CategoryMapper;
import blog.mapper.CommentMapper;
import blog.mapper.TagMapper;
import blog.service.ArticleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private TagMapper tagMapper;
    public List<Article> listRecentArticle(Integer n) {
        return articleMapper.listRecentArticle(n);
    }

    @Override
    public PageInfo<Article> getPageArticleList(Integer pageIndex, Integer pageSize) {
         PageHelper.startPage(pageIndex,pageSize);
         List<Article> articleList = articleMapper.findAll();
         //给每个文章添加分类
        for (Article a:articleList){
            List<CateGory> cateGoryList = categoryMapper.listCateGoryRefByArticleId(a.getArticleId());
            a.setCategoryList(cateGoryList);
        }
         return new PageInfo<>(articleList);
    }

    @Override
    public void deleteArticleById(Integer id)
    {   //删除文章
        articleMapper.deleteArticleById(id);
        //删除这篇文章下的所有评论
        commentMapper.deleteCommentByArticleId(id);
        //删除文章-分类关联表里对应的文章Id
        categoryMapper.deleteArticleRefCateGory(id);
        //删除文章-标签关联表里对应的文章Id
        tagMapper.deleteArticleRefTag(id);
    }

    @Override
    public void addArticle(Article article) {
        //将文章信息添加到文章表
        articleMapper.addArticle(article);
        //将文章与分类之间的关系添加到文章-分类表中
        for (CateGory c:article.getCategoryList()){
            categoryMapper.addArticleCateGory_ref(c.getCateGoryId(),article.getArticleId());
        }
        //将文章与标签之间的关系添加到文章-标签表中
        for (Tag tag:article.getTagList()){
            tagMapper.addArticleTag_ref(tag.getTagId(),article.getArticleId());
        }
    }

    @Override
    public void addDraft(Article article) {
        articleMapper.addArticle(article);
    }

    @Override
    public Article getArticleById(Integer id) {
        return articleMapper.getArticleById(id);
    }

    @Override
    public int getArticleCateGoryCount(Integer id) {
        return articleMapper.getArticleCountOfCategory(id);
    }
}
